<template>
  <view class="goodsEdit">
    <editor
      :style="bodyStyle"
      id="editor"
      show-img-toolbar
      show-img-size
      class="ql-container"
      :placeholder="placeholder"
      @ready="onEditorReady"
      @focus="focusFn"
      @blur="blurFn"
    ></editor>

    <view class="bottomBtn" :style="bottomStyle">
      <view class="u-flex iconList">
        <icon class="iconfont icon-image fz-26" @click="upImg" />
        <icon class="iconfont icon-H- fz-26" data-name="header" :data-value="1" @click.stop="format" />
        <icon class="iconfont icon-H-1 fz-26" data-name="header" :data-value="2" @click.stop="format" />
        <icon class="iconfont icon-line-height fz-22 u-p-b-4" data-name="lineHeight" data-value="2" @click.stop="format" />
        <icon class="iconfont icon-bold fz-26" data-name="bold" @click.stop="format" />
        <icon class="iconfont icon-shuipingfengexian fz-26" @click.stop="insertDivider" />
      </view>
      <view class="u-flex editBtn">
        <button class="btn" @click="editConfig"> 编辑完成</button>
      </view>
    </view>
  </view>
</template>

<script>
import { compressImg } from '@/components/ossutil/ossMult'
export default {
  data() {
    return {
      bodyHeight: this.$store.state.globalData.windowHeight || 0,
      onKeyboardHeight: 0, // 软键盘高度
      placeholder: "开始输入...",
      newImageList: [], // 新加的图片数组
    };
  },
  onLoad(){
    uni.onKeyboardHeightChange(res => { 
      this.onKeyboardHeight = res.height // 软键盘高度
      uni.setStorageSync('onKeyboardHeight', res.height)// 解决ios兼容性bug
    })
  },
  onShow(){
    this.$nextTick(()=>{ // 获取页面高度
      uni.getSystemInfo({
        success: res => {
          this.bodyHeight = res.windowHeight
        }
      })
    })
  },
  onReady() {
      this.placeholder = '在这里开始编辑帮卖介绍'
  },
  computed: {
    bodyStyle(){
      setTimeout(() => {
        this.editorCtx.scrollIntoView()
      }, 500);
      if(this.onKeyboardHeight === 0){
        return `height: ${this.bodyHeight}px;padding-bottom: 132rpx;padding-bottom: calc(132rpx + constant(safe-area-inset-bottom));padding-bottom: calc(132rpx + env(safe-area-inset-bottom));`
      }else{
        return `height: calc(${this.bodyHeight}px - ${this.onKeyboardHeight}px);padding-bottom: 132rpx;`
      }
    },
    bottomStyle(){
      if(this.onKeyboardHeight === 0){
        return `bottom: 0;bottom: constant(safe-area-inset-bottom);bottom: env(safe-area-inset-bottom);`
      }else{
        return `bottom: 0;`
      }
    }
  },
  watch: {
    // 解决ios兼容性bug
    onKeyboardHeight(nval){
      if(nval){
        uni.pageScrollTo({scrollTop: 0})
      }
      this.$forceUpdate()
    }
  },
  methods: {
    // 解决ios兼容性bug
    focusFn(){
      if(this.onKeyboardHeight === 0){
        this.onKeyboardHeight = uni.getStorageSync('onKeyboardHeight') || 0
      }
    },
    // 解决ios兼容性bug
    blurFn(){
      this.onKeyboardHeight = 0
    },
    // 获取富文本实例
    onEditorReady() {
      const that = this
      uni.createSelectorQuery().in(this).select("#editor").context((res) => {
          that.editorCtx = res.context;
          that.editorCtx.setContents({html: that.$store.state.editorObject.html || ""}) // 回显
      }).exec();
    },
    // 图片上传
    upImg() {
      const that = this;
      uni.chooseImage({
        count: 9,
        success: function (res) {
          for (let index = 0; index < res.tempFiles.length; index++) {
            that.editorCtx.insertImage({
              src: res.tempFiles[index].path,
              data: {},
              width: '100%', // 不显示修改尺寸工具，有bug,会超出屏幕
              extClass: 'editorImg', // 去除图片间隙
              success: function () {
                that.newImageList.push(res.tempFiles[index].path) // 本次选择的图片，包括选择后撤销的
              },
            });
          }
        },
      });
    },
    editConfig() {
      const that = this;

      that.editorCtx.getContents({
        success: async function (res) {
          const editorObj = {
            html: "",
            text: res.text.replace(/^[\r\n]+$/g, ''), // 过滤回车符
            image: [],
          }
          let regex = ''
          if(res.html.indexOf('data-local') !== -1){ // 真机临时路径存在于data-local
            regex = new RegExp(/<img [^>]*data-local=['"]([^'"]+)[^>]*>/gi); // /(?<=(src="))[^"]*?(?=")/ig 此正则ios不支持
          }else{
            regex = new RegExp(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi); // /(?<=(src="))[^"]*?(?=")/ig 此正则ios不支持
          }
          res.html.replace(regex, function (match, capture) {
            editorObj.image.push(capture) // 所有图片路径，包括已上传
            return match
          })

          if(editorObj.image.length){ // 存在图片
            for (let i = 0; i < editorObj.image.length; i++) {
              if(that.newImageList.includes(editorObj.image[i])){ // 存在未上传的图片
                const data = await compressImg(editorObj.image[i],375,that) // 上传
                res.html = res.html.replace(regex,function (match, capture) { // 替换临时路径 res.html的src苹果真机为base64，对比会卡死
                  if(capture === editorObj.image[i]){
                    editorObj.image[i] = data.url
                    return `<img src="${data.url}" width="100%" class="editorImg" />`
                  }else{
                    return match
                  }
                })
              }
            }
          }
          // 分割线正则
          const regCutLine = /<\s*hr\s*\/?>/g
          if (editorObj.image.length) {
            editorObj.html = res.html
          } else {
            if (editorObj.text || regCutLine.test(res.html)) {
              editorObj.html = res.html
            } else {
              editorObj.html = ''
            }
          }
          console.log(editorObj.html,'vuex保存的对象');
          that.$store.commit('SET_EDITOR_OBJECT', editorObj)
          uni.hideLoading()
          uni.navigateBack()
        },
      });
    },
    // 样式设置
    format(e) {
      let { name, value } = e.target.dataset;
      if (!name) return; // console.log('format', name, value)
      this.editorCtx.format(name, value);
    },
    insertDivider() {
      this.editorCtx.insertDivider({
        success: function() {
          console.log('插入分割线');
        }
      });
    },
    // undo() {
    //   this.editorCtx.undo();
    // },

    
  },
};
</script>

<style lang="scss" scoped>
.goodsEdit {
  background-color: #FFF;
  position: relative;
  .bottomBtn{
    background-color: #FFF;
    padding: 16rpx 32rpx;
    position: absolute;
    left: 0;
    width: 100%;
    display: flex;
    justify-content: space-between;
    box-shadow: 0 -1px 0 #EEE;
    .iconfont+.iconfont{
      margin-left: 20rpx;
    }
    .editBtn{
      .btn{
        background: #E44435;
        border-radius: 32rpx;
        color: #FFF;
        height: 64rpx;
        line-height: 64rpx;
        font-size: 28rpx;
        padding: 0 20rpx;
      }
    }
  }
}

#editor {
  width: 100%;
  border-top: solid 1px #EEE;
  padding: 32rpx; 
}
</style>